package com.riteny.mybatis.scanner;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.util.List;

/**
 *
 * Provide basic database access methods
 * The target service class needs to extend this abstract class
 * example:
 * public class CasCoreApiRequestService extends BaseService<CasCoreApiRequestMapper>{...}
 *
 * @author tanntly
 * @param <Dao> Extended base repository class
 */
public abstract class BaseService<Dao extends BaseMapper>{
    protected Dao repository;

    public <T> void save(T entity){
        repository.insert(entity);
    }

    public <ID> void delete(ID id){
        repository.delete(id);
    }

    public <T> void update(T entity){
        repository.update(entity);
    }

    public <T> List<T> queryList(SearchCriteria searchCriteria){

        return repository.selectBySearchCriteria(searchCriteria);

    }

    public <T> T query(SearchCriteria searchCriteria){

        List<T> entities = repository.selectBySearchCriteria(searchCriteria);

        if (entities !=null && entities.size()>0)
            return entities.get(0);

        return null;
    }

    public <T> Page<T> queryList(SearchCriteria searchCriteria, Integer page, Integer size){

        return PageHelper.startPage(page,size).doSelectPage(()->repository.selectBySearchCriteria(searchCriteria));

    }

    public <T> Page<T> queryList(SearchCriteria searchCriteria, Integer page, Integer size,String orderBy){

        return PageHelper.startPage(page,size).setOrderBy(orderBy).doSelectPage(()->repository.selectBySearchCriteria(searchCriteria));

    }

    public <T> T query(SearchCriteria searchCriteria,String orderBy){

        List<T> entities = PageHelper.startPage(1,1).setOrderBy(orderBy).doSelectPage(()->repository.selectBySearchCriteria(searchCriteria));

        if (entities !=null && entities.size()>0)
            return entities.get(0);

        return null;
    }

    public <T> List<T> queryList(SearchCriteria searchCriteria,String orderBy){

        return PageHelper.startPage(1,1).setOrderBy(orderBy).doSelectPage(()->repository.selectBySearchCriteria(searchCriteria));

    }
}
